package com.yhuk.oauth.server.service;

import com.yhuk.oauth.server.dao.power.UserDao;
import com.yhuk.oauth.server.model.MyUserDetails;
import com.yhuk.oauth.server.model.SysUser;
import com.yhuk.oauth.server.model.User;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Primary;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.security.oauth2.provider.endpoint.TokenEndpoint;
import org.springframework.stereotype.Service;
import org.springframework.util.Assert;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import java.util.HashSet;
import java.util.Optional;
import java.util.Set;

/**
 * @author xiaolang
 * @version 1.0.0
 */
@Primary
@Service("userService")
public class UserServiceImpl implements UserService{

    private Logger logger = LoggerFactory.getLogger(UserServiceImpl.class);

    @Autowired
    private UserDao userDao;

    @Override
    public UserDetails loadUserByUsername(String loginName) throws UsernameNotFoundException {
        logger.info("登录名称:{}",loginName);
        User user = userDao.loadByLoginName(loginName);
        System.out.println(user);
        if (user==null)
            throw new UsernameNotFoundException("there's no user founded!");
        else
            return UserDetailConverter.convert(user);
    }

    @Override
    public SysUser loadByLoginName(String loginName) {
        Assert.notNull(loginName,"登录名称不能为空");
        return userDao.loadSysUserByLoginName(loginName);
    }

    /**
     * 静态内部类，只在该类使用
     */
    private static class UserDetailConverter {
        static UserDetails convert(User user) {
            return new MyUserDetails(user);
        }
    }
}
